package com.cxx.purchasecharge.component.controller;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.ContactTypeBean;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.BeanConvertUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.ContactType;
import com.cxx.purchasecharge.dal.ContactTypeDao;

@Controller
@RequestMapping ("/contactType")
public class ContactTypeManager
{
    private static final Logger logger = Logger.getLogger (ContactTypeManager.class);

    @Autowired
    private ContactTypeDao contactTypeDao;

    @RequestMapping (value = "/")
    public String redirectToContactTypeManagement (ModelMap model)
    {
        return "contactTypeManagement";
    }

    @RequestMapping (value = "/checkExist", method = RequestMethod.POST)
    public @ResponseBody
    String checkExist (@RequestParam String contactTypeId, @RequestParam String name)
    {
        if (StringUtils.isBlank (contactTypeId))
        {
            // new
            ContactType obj = contactTypeDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long id = Long.parseLong (contactTypeId);
            ContactType contactType = contactTypeDao.findByName (name);
            if (null != contactType && contactType.getId () != id)
            {
                return "false";
            }
        }

        return "true";
    }

    @RequestMapping (value = "/getAllType", method = RequestMethod.POST)
    public @ResponseBody
    String getContactTypes (DataGridRequestForm dataGridRequestForm)
    {
        List <ContactType> units = (List <ContactType>) contactTypeDao.findAll ();

        JSONArray jsonObject = JSONArray.fromObject (units);
        return jsonObject.toString ();
    }

    @RequestMapping (value = "/newContactType", method = RequestMethod.POST)
    public @ResponseBody
    String addContactType (ContactTypeBean contactTypeBean, BindingResult result)
    {
        if (result.hasErrors ())
        {
            logger.error (result.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ContactType contactType = BeanConvertUtils.contactTypeBean2ContactType (contactTypeBean);
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                contactTypeDao.save (contactType);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_CONTACT_TYPE))
                                 .build ();
                logger.error (e.getMessage (), e);
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/updateContactType", method = RequestMethod.POST)
    public @ResponseBody
    String updateContactType (ContactTypeBean contactTypeBean, BindingResult result)
    {
        if (result.hasErrors ())
        {
            logger.error (result.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ContactType contactType = BeanConvertUtils.contactTypeBean2ContactType (contactTypeBean);
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                contactTypeDao.save (contactType);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT_TYPE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/delContactType", method = RequestMethod.POST)
    public @ResponseBody
    String deleteContactType (@RequestParam String ids)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            List <ContactType> contactTypes = new ArrayList <ContactType> ();
            ContactType contactType;
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String typeId : idArr)
                {
                    contactType = new ContactType ();
                    contactType.setId (Long.parseLong (typeId));
                    contactTypes.add (contactType);
                }
            }
            else
            {
                contactType = new ContactType ();
                contactType.setId (Long.parseLong (ids));
                contactTypes.add (contactType);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                contactTypeDao.delete (contactTypes);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT_TYPE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST + " ids=" + ids + " when delete contact type");
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }
}
